import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/family_list_request.dart';
import 'package:elephant_fish/model/family_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/family_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class FamilyJoinPage extends StatefulWidget {
  const FamilyJoinPage({Key key}) : super(key: key);

  @override
  _FamilyJoinPageState createState() => _FamilyJoinPageState();
}

class _FamilyJoinPageState extends State<FamilyJoinPage> {

  List<FamilyEntity> familyList = [];
  bool _loading = false;
  int pageIndex = 1;
  TextEditingController searchController = TextEditingController();
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        _loadData(loadMore: true);
      }
    });
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3d),
      appBar: AppBar(
        backgroundColor: Color(0xff140c3d),
        centerTitle: true,
        leading: GestureDetector(
          child: Icon(
            Icons.arrow_back_ios,
            size: SizeUtil.px(32),
            color: Color(0xfff3f3f3),
          ),
          onTap: () {
            Navigator.pop(context);
          },
        ),
        title: Text(
          '加入家族',
          style: TextStyle(fontSize: SizeUtil.px(32), color: Color(0xfff5f5f5)),
        ),
      ),
      body: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: SizeUtil.px(557),
                height: SizeUtil.px(68),
                decoration: BoxDecoration(
                    color: Color(0xff2b244d),
                    borderRadius:
                    BorderRadius.all(Radius.circular(SizeUtil.px(53)))),
                child: Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: SizeUtil.px(28)),
                      child: Icon(
                        Icons.search,
                        color: Color(0xff59527a),
                        size: SizeUtil.px(40),
                      ),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Expanded(
                        child: TextField(
                          controller: searchController ,
                          decoration: InputDecoration(
                            isCollapsed: true,
                            contentPadding: EdgeInsets.all(0),
                            border: InputBorder.none,
                            hintText: '请输入家族名称或ID',
                            hintStyle: TextStyle(
                                color: Color(0xff59527a),
                                fontSize: SizeUtil.px(33)),
                          ),
                          style: TextStyle(
                              color: Color(0xff59527a),
                              fontSize: SizeUtil.px(33)),
                        ))
                  ],
                ),
              ),
              SizedBox(
                width: SizeUtil.px(25),
              ),
              Container(
                  width: SizeUtil.px(121),
                  height: SizeUtil.px(55),
                  decoration: BoxDecoration(
                      color: Color(0xffff215d),
                      borderRadius: BorderRadius.all(
                          Radius.circular(SizeUtil.px(53)))),
                  child:
                  InkWell(
                    child: Align(
                        alignment: Alignment.center,
                        child: Text(
                          '搜索',
                          style: TextStyle(
                              color: Color(0xfff3f3f3),
                              fontSize: SizeUtil.px(26)),
                        )),
                    onTap: (){
                      searchFamily();
                    },
                  )
              ),
            ],
          ),
          Expanded(child: ListView.builder(
              itemCount: familyList.length,
              controller: _scrollController,
              shrinkWrap: true,
              itemBuilder:(context,index){
                return FamilyList(familyEntity: familyList[index],);
              }
          ),),
          SizedBox(height: SizeUtil.px(30),),
        ],
      ),
    );
  }

  _loadData({loadMore = false})async {
    _loading = true;
    if(!loadMore){
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = FamilyListRequest();
    request.add('type', 2).add('page', pageIndex).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode': '-1'},);
        },
      ));
    }else if(result['code'] == 0){
      List<FamilyEntity> list = List();
      List<Map<String,dynamic>> listMap = new List<Map<String, dynamic>>.from(result['data']['data']);
        for(int i = 0;i < listMap.length; i++){
          list.add(FamilyEntity.fromJson(listMap[i]));
        }
      setState(() {
        if (loadMore) {
          if (list.isNotEmpty) {
            //合成一个新数组
            familyList = [...familyList, ...list];
            pageIndex++;
          }
        } else {
          familyList = list;
        }
      });
      Future.delayed(Duration(milliseconds: 1000), () {
        _loading = false;
      });
    }
  }

  Future<void> searchFamily() async {
    String search = searchController.text;

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = FamilyListRequest();
    request.add('type', 2).add('name', search).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode': '-1'},);
        },
      ));
    }else if(result['code'] == 0) {
      List<FamilyEntity> list = List();
      List<Map<String, dynamic>> listMap = new List<
          Map<String, dynamic>>.from(result['data']['data']);
      for (int i = 0; i < listMap.length; i++) {
        list.add(FamilyEntity.fromJson(listMap[i]));
      }
      setState(() {
        familyList = list;
      });
    }

  }
}
